#include "udp_client.hpp"
using namespace std;

static void usage(string proc){
    cout << "Usage:\t\n" << proc << " serverip serverport\n" << endl;
}

void* receive(void* args){
    int sock = *(static_cast<int*>(args));
    while(true){
        char buffer[2048];
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        int n = recvfrom(sock, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&temp, &len);
        if(n > 0){
            buffer[n] = 0;
            cout << buffer << endl;
        }
    }
}

int main(int argc, char* argv[]){
    if(argc != 3){
        usage(argv[0]);
        exit(USAGE_ERR);
    }

    string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]);

    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if(sock < 0){
        std::cerr << "creat socket error: " << strerror(errno) << std::endl;
            exit(SOCKET_ERR);
    }

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    pthread_t tid;
    pthread_create(&tid, nullptr, receive, &sock);

    while(true){
        
        string message;
        cout << "[client]# ";
        //cin >> message;
        getline(cin, message);

        //发送
        sendto(sock, message.c_str(), message.size(), 0, (struct sockaddr*)&server, sizeof(server));

        //接收

    }

    return 0;
}